package com.sx.manage.interceptor;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.sx.cache.Cache;
import com.sx.cache.Session;
import com.sx.common.util.json.JackJsonUtil;
import com.sx.manage.biz.login.IMSystemConsumerLoginBiz;
import com.sx.manage.exception.MAjaxErrorException;
import com.sx.manage.exception.MNotHaveLoginException;
import com.sx.manage.exception.MNotHaveLoginExceptionAjax;
import com.sx.manage.exception.MViewAndModelException;
import com.sx.manage.service.function.FunctionInfoWebService;
import com.sx.manage.util.SessionManager;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.constants.type.consumer.MConsumersNatures;
import com.sx.model.manage.mybatis.vo.consumer.login.MConsumerLoginVO;

/**
 * spring 过滤器 
 * @author 139570
 *
 */
/**
 * spring 过滤器
 * 
 * @author 139570
 *
 */
public class MSessionInterceptor implements HandlerInterceptor {

	private Logger _log = LoggerFactory.getLogger(this.getClass());

	protected Cache redisCache;

	@Resource(name = "functionInfoWebService")
	private FunctionInfoWebService functionInfoWebService;

	@Resource(name = "mSystemConsumerLoginBizImpl")
	private IMSystemConsumerLoginBiz mSystemConsumerLoginBizImpl;
	
	public IMSystemConsumerLoginBiz getmSystemConsumerLoginBizImpl() {
		return mSystemConsumerLoginBizImpl;
	}
	public void setmSystemConsumerLoginBizImpl(IMSystemConsumerLoginBiz mSystemConsumerLoginBizImpl) {
		this.mSystemConsumerLoginBizImpl = mSystemConsumerLoginBizImpl;
	}
	public Logger get_log() {
		return _log;
	}
	public void set_log(Logger _log) {
		this._log = _log;
	}
	public FunctionInfoWebService getFunctionInfoWebService() {
		return functionInfoWebService;
	}
	public void setFunctionInfoWebService(FunctionInfoWebService functionInfoWebService) {
		this.functionInfoWebService = functionInfoWebService;
	}

	public Cache getRedisCache() {
		return redisCache;
	}
	public void setRedisCache(Cache redisCache) {
		this.redisCache = redisCache;
	}
	public List<String> allowUrls;// 还没发现可以直接配置不拦截的资源，所以在代码里面来排除
	public List<String> getAllowUrls() {
		return allowUrls;
	}
	public void setAllowUrls(List<String> allowUrls) {
		this.allowUrls = allowUrls;
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
		//因为 replace之后，路径可能就是""
		if("".equals(requestUrl)){
			requestUrl="/";
		}
		//判断是否为ajax请求，默认不是  
        boolean isAjaxRequest = false;  
        if(!StringUtils.isBlank(request.getHeader("x-requested-with")) && request.getHeader("x-requested-with").equals("XMLHttpRequest")){  
            isAjaxRequest = true;  
        } 
        _log.info("请示是否为ajax 请求isAjaxRequest={}",isAjaxRequest);
		// 过滤掉不需要权限的访问
		if (!allowUrls.isEmpty()) {
			for (String url : allowUrls) {
				if (requestUrl.contains(url) || requestUrl.equals("/")) {
					_log.debug("不用过滤的url=" + url);
					return true;
				}
			}
		}
		_log.debug("过滤地址：" + requestUrl);
		Session session = SessionManager.instance(request, response, redisCache);
		session.expire(MSystemConstants.SESSION_TIME_SET_UP);
		// 判断当前的用户是否登陆
		if (!session.istokenexists()) {
			String user_id = session.get("user_id");
			_log.debug("根据token不存在判定，还没有登录，或登录超时，请重新登录:url={},user_id={}",requestUrl,user_id);
			// 未登录 跳转到登录页面
			redisCache.set("error", "你还没有登录，或登录超时，请重新登录");
			notHaveLoginException(isAjaxRequest,requestUrl);
		}
		String userJson = session.get("user");
		_log.info("用户信息user={}",userJson);
		if (StringUtils.isBlank(userJson)) {
			_log.debug("redis内获取用户信息为空，userJson={}判定用户超时：",userJson);
			notHaveLoginException(isAjaxRequest,requestUrl);
		}
		// 获取 护具
		MConsumerLoginVO user_ = JackJsonUtil.jsonToJavaBean(userJson, MConsumerLoginVO.class);
		if (null == user_) {
			_log.debug("json转换为MConsumerLoginVO is null={}，判断用户超时{}" ,(null == user_),userJson);
			notHaveLoginException(isAjaxRequest,requestUrl);
		}
		_log.debug("根据获取用户信息：" + ( user_.getConsumer_name()));
		
		if (mSystemConsumerLoginBizImpl.validate_authority(MConsumersNatures.USER_CENTER,requestUrl,user_.getConsumer_id(),null).isSuccess()) {
			session.put(MSystemConstants.CURRENT_URL, requestUrl);
			if (null != session.get(MSystemConstants.CURRENT_URL_ERROR_MESSAGE)) {
				session.put(MSystemConstants.CURRENT_URL_ERROR_MESSAGE, null);
			}
			return true;
		} else {
			// 空字符串直接调转到起始页
			if(isAjaxRequest){
	        	_log.debug("无权限 ajax 跳转提示requestUrl:" + requestUrl);
	            throw new MAjaxErrorException();// 返回到配置文件中定义的路径
	        }else{
	        	_log.debug("无权限 view 跳转提示requestUrl:" + requestUrl);
	        	throw new MViewAndModelException();// 返回到配置文件中定义的路径
	        }
		}
	}
	/** 判断是否为ajax 请求**/
	private void notHaveLoginException(Boolean flag,String requestUrl) {
		//判断是否为ajax请求，默认不是  
        if(flag){
        	_log.debug("登录超时或未登录 ajax 跳转提示requestUrl:" + requestUrl);
            throw new MNotHaveLoginExceptionAjax();// 返回到配置文件中定义的路径
        }else{
        	_log.debug("登录超时或未登录  view 跳转提示requestUrl:" + requestUrl);
        	throw new MNotHaveLoginException();// 返回到配置文件中定义的路径
        }
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		
	}
}
